<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
import { ElMessage } from "element-plus";
import Vcode from "vue3-puzzle-vcode";
let router = useRouter();
const imgs = ref([
  "https://img1.baidu.com/it/u=3550955980,4041911386&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500",
  "https://pic.rmb.bdstatic.com/bjh/a57559753abfc2172255e5bb38eea7534635.jpeg@h_1280",
]);
const isshow = ref(false); // 控制验证码显示
const isVcodePassed = ref(false); // 验证码是否通过
const formModel = reactive({
  user: "",
  pass: "",
});

const formRules = reactive({
  user: [
    { required: true, message: "请输入账号" },
    { min: 4, max: 20, message: "账号长度需要在4到20位之间" },
  ],
  pass: [
    { required: true, message: "请输入密码" },
    { min: 6, max: 20, message: "密码长度需要在6到20位之间" },
  ],
});

// 验证码通过后调用的登录逻辑
const handleLogin = async () => {
  try {
    let response = await axios.get("http://localhost:3000/login", {
      params: { user: formModel.user, pass: formModel.pass },
    });
    if (response.data.code === 200) {
      let accessToken = response.data.accessToken;
      let refreshToken = response.data.refreshToken;
      // 将 token 存储在 localStorage 中
      localStorage.setItem("accessToken", accessToken);
      localStorage.setItem("refreshToken", refreshToken);
      localStorage.setItem("name", response.data.name);
      router.push("/home"); // 登录成功后跳转到首页
      ElMessage({
        message: "登录成功",
        type: "success",
      });
    } else {
      ElMessage.error("用户名或密码错误");
    }
  } catch (error) {
    ElMessage.error("登录失败");
  }
};

// 点击登录按钮的逻辑
const Login = async () => {
  // 如果验证码还没有通过，显示验证码
  if (!isVcodePassed.value) {
    isshow.value = true;
    return;
  }

  // 验证码通过后，执行登录逻辑
  handleLogin();
};

// 验证码成功回调
const onSuccess = () => {
  isVcodePassed.value = true; // 验证码通过
  isshow.value = false; // 隐藏验证码
  handleLogin(); // 验证成功后执行登录逻辑
};

// 验证码失败回调
const onFail = () => {
  isshow.value = false; // 验证码验证失败后隐藏验证码
  isVcodePassed.value = false; // 重置验证状态
  ElMessage.error("验证失败");
};
</script>

<template>
  <div id="Login">
    <div class="img">
      <img
        src="https://img1.baidu.com/it/u=4152366307,3892585726&fm=253&fmt=auto&app=138&f=JPEG?w=987&h=800"
        class="tx"
      />
      <div class="login">
        <div class="box">
          <el-form ref="form" :rules="formRules" :model="formModel">
            <el-form-item prop="user">
              <el-input v-model="formModel.user" placeholder="请输入用户名" clearable />
            </el-form-item>
            <el-form-item prop="pass">
              <el-input
                v-model="formModel.pass"
                type="password"
                placeholder="请输入密码"
                show-password
                clearable
              />
            </el-form-item>
            <el-form-item >
             <button type="button" style="color: #fff;background-color: rgba(0,0,0,0.5);border: none;" @click.stop="router.push('/phone')">选择短信登录</button>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="Login">登录</el-button>
          <el-button type="info" @click="router.push('/register')">注册</el-button>
        </div>
      </div>
    </div>
    <Vcode :show="isshow" :src="imgs" @success="onSuccess" @fail="onFail" />
  </div>
</template>

<style lang="scss" scoped>
#Login {
  width: 100%;
  height: 100%;
  background: linear-gradient(to right top, #ecf5ff, #c6e2ff);

  .img {
    width: 100%;
    height: 100vh;
    background-image: url("https://img1.baidu.com/it/u=3743680466,2149120321&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=500");
    background-size: cover;
    background-position: center;

    .tx {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      position: absolute;
      top: 34%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 1;
    }

    .login {
      width: 500px;
      height: 300px;
      background-color: rgba(0, 0, 0, 0.5);
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;

      .box {
        width: 50%;
        height: 100px;
        margin: 0 auto;
        margin-top: 60px;
      }
    }
  }
}
</style>
